--render fancy background stuff
local priority = 1

local backgrounds = {}
backgrounds[1] = {x = 0, y = -720}
backgrounds[2] = {x = 0, y = 0}
backgrounds[3] = {x = 0, y = 720}
backgrounds[4] = {x = -1280, y = -720}
backgrounds[5] = {x = -1280, y = 0}
backgrounds[6] = {x = -1280, y = 720}
backgrounds[7] = {x = 1280, y = -720}
backgrounds[8] = {x = 1280, y = 0}
backgrounds[9] = {x = 1280, y = 720}

local backgrounds2 = {}
backgrounds2[1] = {x = 0, y = -720}
backgrounds2[2] = {x = 0, y = 0}
backgrounds2[3] = {x = 0, y = 720}
backgrounds2[4] = {x = -1280, y = -720}
backgrounds2[5] = {x = -1280, y = 0}
backgrounds2[6] = {x = -1280, y = 720}
backgrounds2[7] = {x = 1280, y = -720}
backgrounds2[8] = {x = 1280, y = 0}
backgrounds2[9] = {x = 1280, y = 720}

EntitySystem.rendersystem("drawBG", priority, function()
  updateBackPos()
  camera:detach()
  love.graphics.setColor(color.white)
  love.graphics.draw(background)
  
  --Draw parallax asteroids in background
  for i = 1, 9 do
    love.graphics.setColor(90,90,90,255)
      love.graphics.draw(back2, backgrounds[i].x, backgrounds[i].y)
      love.graphics.setColor(54,54,54,255)
      love.graphics.draw(back3, backgrounds2[i].x, backgrounds2[i].y)
  end
    
  camera:attach()
end)

function updateBackPos()
    if player and player.physics then
    local x,y = player.physics.body:getLinearVelocity()
    
    --Update all background asteroid positions
    for i = 1, 9 do
      backgrounds[i].x = backgrounds[i].x - x/6000
      backgrounds[i].y = backgrounds[i].y - y/6000
      
      backgrounds2[i].x = backgrounds2[i].x - x/1500
      backgrounds2[i].y = backgrounds2[i].y - y/1500
      
      --If an image gets out of bounds, snap it to the other side to create an "infinite" field
      if backgrounds[i].x < -1280 then
        backgrounds[i].x = 1280
      end
      if backgrounds[i].y < -720 then
        backgrounds[i].y = 720
      elseif backgrounds[i].y > 720 then
        backgrounds[i].y = -720
      end
      
      if backgrounds2[i].x < -1280 then
        backgrounds2[i].x = 1280
      end
      if backgrounds2[i].y < -720 then
        backgrounds2[i].y = 720
      elseif backgrounds2[i].y > 720 then
        backgrounds2[i].y = -720
      end
    end
    
  end
end
